#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
import os
import subprocess
import random, string, uuid
from web import models

from django.contrib.auth import authenticate


class HostManager(object):
    '''用户登录堡垒机的交互程序'''
    def get_session_id(self, bind_host_obj, tag):
        '''apply  session id'''
        session_obj = models.Session(user_id= self.user.id, bind_host=bind_host_obj, tag=tag)

        session_obj.save()
        # print('session id:', session_obj)
        return session_obj

    def interactive(self):
        '''交互脚本'''
        print('-----run-----')
        self.user = None
        count = 0
        while count < 3:
            username = input("username:").strip()
            password = input("password:").strip()
            user = authenticate(username=username, password=password)
            if user:
                # print("user can access hosts", user.bind_hosts.all())
                # print("user can access hosts_group", user.host_groups.all())
                print("welcome %s".center(50, "-") % user.name)
                self.user = user
                break
            else:
                print("Wrong username or password")
            count += 1
        else:
            exit("Too many login try,bey")

        if self.user:
            while True:
                for index, host_groups in enumerate(self.user.host_groups.all()):
                    print("%s.\t%s[%s]" % (index, host_groups.name, host_groups.bind_hosts.count()))
                print("z.\t未分组[%s]" % (self.user.bind_hosts.count()))
                choise = input("%s>>>:" % self.user.name).strip()
                selected_host_group = None
                if len(choise) == 0: continue
                if choise.isdigit():
                    choise = int(choise)
                    if choise >= 0 and choise <= index:
                        selected_host_group = list(self.user.host_groups.all())[choise]
                        # while True:
                        #     for index, bind_host in enumerate(selected_host_group.bind_hosts.all()):
                        #         print(index, bind_host)
                        #     choise = input("%s>>>:" % self.user.name).strip()
                        #     if choise.isdigit():
                        #         choise = int(choise)
                        #         if choise >=0 and choise <= index:
                        #             print("going to login.....", selected_host_group.bind_hosts.all()[choise])

                elif choise == "z":
                    selected_host_group = self.user
                    # while True:
                    #     for index, bind_host in enumerate(selected_host_group.bind_hosts.all()):
                    #         print(index, bind_host)
                    #     choise = input("%s>>>:" % self.user.name).strip()
                    #     if choise.isdigit():
                    #         choise = int(choise)
                    #         if choise >= 0 and choise <= index:
                    #             print("going to login.....", selected_host_group.bind_hosts.all()[choise])
                if selected_host_group:
                    while True:
                        for index, bind_host in enumerate(selected_host_group.bind_hosts.all()):
                            print(index, bind_host)
                        choise = input("%s>>>:" % self.user.name).strip()
                        if choise.isdigit():
                            choise = int(choise)
                            if choise >= 0 and choise <= index:
                                print("going to login.....", selected_host_group.bind_hosts.all()[choise])
                                bind_host = selected_host_group.bind_hosts.all()[choise]
                                ssh_tag = uuid.uuid4()
                                session_obj= self.get_session_id(bind_host, ssh_tag)
                                monitor_script = subprocess.Popen("sh /opt/CrazyEye/backend/session_tracker.sh %s %s" %(ssh_tag, session_obj.id), shell=True,
                                                                  stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                                #print(monitor_script.stdout.read())
                                subprocess.run("sshpass -p%s ssh %s@%s -E %s -o StrictHostKeyChecking=no" % (
                                bind_host.host_user.password, bind_host.host_user.username, bind_host.host.ip_addr,
                                ssh_tag), shell=True)

                                os.remove(ssh_tag)
                        elif choise == "b":
                            break
